package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final StringRedisTemplate stringRedisTemplate;

    public UserServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Result gdCode(String phone, HttpSession session) {
        //校验手机格式
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机格式错误");
        }

        //生成验证码
        String Code = RandomUtil.randomNumbers(6);
//        //保存验证码到session
//        session.setAttribute("code",Code);
        log.info("验证码：{}",Code);

        //保存验证码到redis
        stringRedisTemplate.opsForValue().set("code:"+phone,Code,2, TimeUnit.MINUTES);
        return null;
    }

    @Override
    public Result selectByPhone(LoginFormDTO loginForm,HttpSession session) {
        //校验手机格式
        String code = stringRedisTemplate.opsForValue().get("code:" + loginForm.getPhone());
        if (code == null || ! code.equals(loginForm.getCode())) {
            // 验证码错误
            return Result.fail("验证码错误");
        }

        //查找用户
        User user = query().eq("phone", loginForm.getPhone()).one();
        UserDTO userDTO = new UserDTO();
        //判断用户是否为新用户
        if(user == null){
            //是新用户新增到数据库
            User newUser = new User();
            BeanUtils.copyProperties(loginForm,newUser);
            newUser.setCreateTime(LocalDateTime.now());

            //给用户生成随机昵称
            String nickname = "user_" + RandomUtil.randomNumbers(10);
            newUser.setNickName(nickname);

            //保存到数据库
            this.save(newUser);
            BeanUtils.copyProperties(newUser,userDTO);
            return Result.ok(userDTO);
        }
        BeanUtil.copyProperties(user,userDTO);
        //将UserDTO对象转换为hash结构
        Map<String, Object> userMap = BeanUtil.beanToMap(
                userDTO,
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? null : fieldValue.toString())
        );

        //生成token
        String token = UUID.randomUUID().toString(true);
        String tokenKey = "loginToken:"+token;

        //保存用户到redis
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置token的过期时间
        stringRedisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);

        return  Result.ok(token);


    }
}
